<?php
// +----------------------------------------------------------------------
// | Bwsaas
// +----------------------------------------------------------------------
// | Copyright (c) 2015~2020 http://www.buwangyun.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Gitee ( https://gitee.com/buwangyun/bwsaas )
// +----------------------------------------------------------------------
// | Author: buwangyun <hnlg666@163.com>
// +----------------------------------------------------------------------
// | Date: 2020-9-28 10:55:00
// +----------------------------------------------------------------------

namespace app\manage\controller\member;

use app\common\model\MemberMiniappAudit;
use app\common\model\MemberMiniappTemplate;
use buwang\exception\MiniappException;
use buwang\facade\AliPay;
use buwang\facade\WechatProgram;
use app\common\model\MemberPayment;
use app\common\model\MemberMiniapp;
use buwang\base\MemberBaseController;
use think\facade\Db;
use think\facade\View;

class Setting extends MemberBaseController
{
    public function initialize()
    {
        parent::initialize();
        $errMsg = '';
        if ($this->user->lock_config) $errMsg = '你账户锁定配置权限';
        if ($this->user->parent_id) $errMsg = '仅顶级管理员有权限访问';
        if (!$this->member_miniapp_id) $errMsg = '未找到所属应用,请先开通应用';
        if($errMsg != '') throw new MiniappException($errMsg, 403);
        self::isMemberAppAuth();
        $this->model = new MemberMiniapp();
    }

    public function index()
    {
        //日期
        $date = date('Y-m-d', time());
        //站点名称
        $web_name = bw_config('web_config.web_name');
        //微信支付信息
        $wechat = [
            'is_tpa' => 0,
            'tpa_appid' => '',
            'tpa_mch_id' => '',
            'mch_id' => '',
            'key' => '',
            'cert_path' => '',
            'key_path' => '',
        ];
        $wechat_payment = MemberPayment::where(['apiname' => 'wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
        $wechat_payment && $wechat = array_merge($wechat, json_decode($wechat_payment['config'], true));
        //支付宝支付信息
        $alipay = [];
        $alipay_payment = MemberPayment::where(['apiname' => 'alipay', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
        if ($alipay_payment) $alipay = json_decode($alipay_payment['config'], true);
        //头条支付信息
        $tt_wechat = [
            'mp_toutiao_token' => '',
            'mp_toutiao_salt' => '',
        ];
        $tt_payment = MemberPayment::where(['apiname' => 'tt_wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
        if ($tt_payment) $tt_wechat = json_decode($tt_payment['config'], true);

        //TODO 修改公众号单独授权URL
        //开放平台授权验证url https://buwangyun.com/api/wechat_auth/$APPID$/server
        $APPID = $this->member_miniapp['mp_appid'] ?: '$APPID$';
        $navbar_url = "{$this->request->domain()}/api/wechat_auth/{$APPID}/server";

        //开放平台小程序管理
        //is_commit = 1、2、3、4
        //1、基础信息设置 2、上传代码 3、提交审核 4、发布小程序
        $view['is_authorize'] = 0;//标识已经认证授权过小程序
        $view['audit']['is_commit'] = 1;
        $view['audit']['state'] = 0;//没有查询到小程序提交记录(还没有进行过提交)
        //获取可升级的版本
        $view['update'] = MemberMiniappTemplate::where(['member_miniapp_id' => $this->member_miniapp->id])->field('template_id,version,update_time')->order('template_id desc')->find();
        if(!$view['update']) $view['update']['template_id'] = 0;
        if ($this->member_miniapp->miniapp->is_openapp && $this->member_miniapp->miniapp_appid) {//是开放平台并且有appid(已经授权)
            $miniapp = WechatProgram::getWechatObj($this->member_miniapp_id);//获取小程序开放平台操作实例
            if ($miniapp) {
                $view['is_authorize'] = 1;
                $view['auditid']['status'] = -1;
                $audit = MemberMiniappAudit::where(['member_miniapp_id' => $this->member_miniapp_id, 'member_id' => $this->user->id])->find(); //查询状态
                //查询到有提交记录
                if ($audit) {
                    $view['audit'] = $audit;
                    //已经提交审核，查询审核状态 is_commit = 3 && state = 1
                    //state为0已经发布代码成功，state为1待发布代码
                    if ($view['audit']['is_commit'] == 3 && $view['audit']['state'] == 1) {
                        $rel = $miniapp->code->getLatestAuditStatus();//查询最新一次提交的审核状态
                        if ($rel['errcode'] == 0) {
                            $view['auditid'] = $rel;
                            if ($rel['status'] == 1) {//1审核被拒绝 0审核成功2审核中3已撤回
                                $view['audit']->state = 0;
                                $view['audit']->is_commit = 2;//重新上传
                                $view['audit']->save();
                            } elseif ($rel['status'] == 0){
                                $view['audit']->state = 1;
                                $view['audit']->is_commit = 4;//第4步骤要发布代码
                                $view['audit']->save();
                            }
                        }
                    }
                    //已发布的代码 is_commit = 4 && state = 0
                    $view['update_var'] = 0;
                    if ($view['audit']['is_commit'] == 4 && $view['audit']['state'] == 0) {//state为0已经发布代码成功，state为1待发布代码
                        if ($view['update']['template_id'] > $this->member_miniapp->template_id) {//有新版本 重新上传小程序代码
                            $view['update_var'] = 1;
                            $view['audit']['is_commit'] = 2;//如果有新代码重置is_commit=2
                        }
                    }
                    if (!file_exists(public_path() . $view['audit']['trial_qrcode'])) {
                        $view['audit']['trial_qrcode'] = '';
                    }
                } else {
                    $view['audit']['state'] = 0;//没有查询到小程序提交记录(还没有进行过提交)
                }
            }
        }
        if ($this->request->isAjax()) {
            return $this->success('success', ['view'=>$view,'date'=>$date,'update_var'=>$view['update_var'] ?? 0,'web_name'=>$web_name,'navbar_url'=>$navbar_url,'wechat'=>$wechat,'alipay'=>$alipay,'tt_wechat'=>$tt_wechat]);
        }else{
            View::assign($view);
            View::assign('date', $date);
            View::assign('update_var', $view['update_var'] ?? 0);
            View::assign('web_name', $web_name);
            View::assign('navbar_url', $navbar_url);
            View::assign('wechat', $wechat);
            View::assign('alipay', $alipay);
            View::assign('tt_wechat', $tt_wechat);

            return view();
        }

    }

    /**
     * 租户应用配置信息编辑
     * @param int $id 租户应用ID
     * @return \think\Response|\think\response\View
     */
    public function edit($id = 0)
    {
        if (request()->isPost()) {
            $param = request()->only(['appname','miniapp_appid','miniapp_secret','mp_appid','mp_secret','mp_token','mp_aes_key','tt_appid','tt_secret']);
            $row = $this->model->find($this->member_miniapp_id);
            if (!$row) return $this->error('记录不存在');
            //TODO 参数验证
            $this->model->startTrans();
            try {
                $row->save($param);
                $this->model->commit();
            } catch (\Exception $e) {
                $this->model->rollback();
                return $this->error('编辑失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('编辑成功');
        }
        return $this->error('请求方式错误');
    }

    public function wechat()
    {
        if (request()->isPost()) {
            $param = request()->post();
            $wechat = [
                'is_tpa' => $param['is_tpa'],//是否微信服务商 0=独立商户,1=微信服务商
                'tpa_appid' => $param['is_tpa'] == 1 ? $param['tpa_appid'] : '',//服务商appid
                'tpa_mch_id' => $param['is_tpa'] == 1 ? $param['tpa_mch_id'] : '',//服务商商户号
                'mch_id' => $param['mch_id'],//商家商户号
                'key' => $param['key'],//商家secret
                'cert_path' => $param['cert_path'],//商家支付证书
                'key_path' => $param['key_path'],//商家支付密钥
            ];
            $data = [
                'apiname' => 'wechat',
                'member_id' => $this->uid,
                'member_miniapp_id' => $this->member_miniapp_id,
                'config' => json_encode($wechat)
            ];

            $wechat_payment = MemberPayment::where(['apiname' => 'wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
            $memberPayment = $wechat_payment ? $wechat_payment : new MemberPayment();

            Db::startTrans();
            try {
                //更新微信支付信息
                $memberPayment->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('修改失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('修改成功');
        }
    }

    public function alipay()
    {
        if (request()->isPost()) {
            $param = request()->post();

            $data = [
                'apiname' => 'alipay',
                'member_id' => $this->uid,
                'member_miniapp_id' => $this->member_miniapp['id'],
                'config' => json_encode($param)
            ];

            $wechat_payment = MemberPayment::where(['apiname' => 'alipay', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
            if ($wechat_payment) $memberPayment = $wechat_payment;
            else $memberPayment = new MemberPayment();

            Db::startTrans();
            try {
                $memberPayment->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('修改失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('修改成功');
        }
    }

    /**保存头条微信支付配置
     * @return \think\Response
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function tt_wechat()
    {
        if (request()->isPost()) {
            $param = request()->post();

            $data = [
                'apiname' => 'tt_wechat',
                'member_id' => $this->uid,
                'member_miniapp_id' => $this->member_miniapp['id'],
                'config' => json_encode($param)
            ];

            $wechat_payment = MemberPayment::where(['apiname' => 'tt_wechat', 'member_id' => $this->uid, 'member_miniapp_id' => $this->member_miniapp['id']])->find();
            if ($wechat_payment) $memberPayment = $wechat_payment;
            else $memberPayment = new MemberPayment();

            Db::startTrans();
            try {
                $memberPayment->save($data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                return $this->error('修改失败', ['errorMsg' => $e->getMessage()]);
            }
            return $this->success('修改成功');
        }
    }

    public function test1()
    {
        $data=[
            'bw_member_app_id'=>'4',
            'notify_url'=>'',
            'attach'=>'alipay',
            'title'=>'111',
            'orderId'=>'20240727104900',
            'totalAmount'=>'1',
        ];
        $res = AliPay::bwUnifiedOrder($data);
        return $this->success('修改成功',$res);
    }
}
